package _8_IO._2_InputStream;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 *
 * InputStream
 *
 * 学习出处：https://www.liaoxuefeng.com/wiki/1252599548343744/1298069163343905
 *
 */
public class _1_InputStreamTest {

     //--------------------
     //  InputStream
     //--------------------

    /**
     * FileInputSteam读取文件所有字节
     *
     * 说明：FileInputStream 是InputStream的子类。FileInputStream是从文件流中读取数据
     */
    @Test
    public void readFile() throws IOException {
        String path = "C:\\";
        String fileName = "aow_drv.log";
        // 创建一个FileInputStream对象
        InputStream inputStream = new FileInputStream(path + fileName);
        for(;;){
            // 反复调用read()方法，直到返回-ReaderTest
            int n = inputStream.read();
            if(n == -1){
                break;
            }
            // 打印byte的值
            System.out.println(n);
        }
        // 关闭流
        inputStream.close();
    }

    /**
     * 对readFile改进，完善异常处理
     *
     * 说明：需要用try ... finally来保证InputStream在无论是否发生IO错误的时候都能够正确地关闭
     *
     * @throws IOException
     */
    @Test
    public void readFile2() throws IOException{
        String path = "C:\\";
        String fileName = "aow_drv.log";
        InputStream inputStream = null;
        int num;
        try {
            inputStream = new FileInputStream(path + fileName);

            while( (num = inputStream.read()) != -1){
                System.out.println(num);
            }
        }
        finally {
            if(inputStream != null) {
                inputStream.close();
            }
        }
    }


    /**
     * 对readFile2改进，简化异常
     *
     * 说明：利用Java 7引入的新的try(resource)的语法，只需要编写try语句，让编译器自动为我们关闭资源
     */
    @Test
    public void readFile3() throws IOException {
        String path = "C:\\";
        String fileName = "test.txt";
        try(InputStream inputStream = new FileInputStream(path + fileName)){
            int num;
            while ( (num = inputStream.read()) != -1){
                System.out.println(num);
            }
        }// 编译器在此自动为我们写入finally并调用close()
    }

    //--------------------
    //  InputStream - 缓冲
    //--------------------

    /**
     *
     * 定义缓冲区，读取文件
     *
     * @throws IOException
     */
    @Test
    public void readFile4() throws IOException {
        String path = "C:\\";
        String fileName = "test.txt";
        try(InputStream inputStream = new FileInputStream(path + fileName)){
            //定义1000个字节的缓冲区
            byte[] bytes = new byte[1000];
            int num;
            //读取到缓冲区
            while( (num = inputStream.read(bytes)) != -1){
                System.out.println(num);
            }
        }
    }

    //-------------------------------------
    //  InputStream - ByteArrayInputStream
    //-------------------------------------



}
